package com.geek.factory.security;

import com.geek.factory.entity.*;
import com.geek.factory.mapper.UserMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/7/7
 *
 * 自定义SecurityUserDetailsService  处理Security的认证逻辑
 */
@Service
public class SecurityUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    //基于Security认证的登录逻辑
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //封装查询条件   通过管理员姓名，查询当前管理员拥有的角色、权限信息
        /**
         * SELECT t.id,t.birthday,t.gender,t.username,t.password,t.remark,t.station,t.telephone,t.avatar,
         * r.id AS joina_id,r.name,r.keyword,r.description,
         * p.id AS joinb_id,p.name AS joina_name,p.keyword AS joina_keyword,p.description AS joina_description
         * FROM user t
         * LEFT JOIN user_role ur ON (ur.user_id = t.id)
         * LEFT JOIN role r ON (r.id = ur.role_id)
         * LEFT JOIN role_permission rp ON (rp.role_id = r.id)
         * LEFT JOIN permission p ON (p.id = rp.permission_id)
         * WHERE (t.username = ?)
         */
        MPJLambdaWrapper<User> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(User.class)
                .selectCollection(Role.class , User::getRoles)
                .leftJoin(UserRole.class , "ur" , UserRole::getUserId , User::getId)
//                .leftJoin(Role.class , "r" , Role::getId , UserRole::getRoleId)
//                .eq(StringUtils.hasLength(username) , User::getUsername , username);
                .leftJoin(Role.class , "r" , Role::getId , UserRole::getRoleId);

        // 判断是用户名还是手机号
        if (username.matches("^1[3-9]\\d{9}$")) {
            // 手机号格式，通过手机号查询
            wrapper.eq(StringUtils.hasLength(username) , User::getPhone , username);
        } else {
            // 用户名格式，通过用户名查询
            wrapper.eq(StringUtils.hasLength(username) , User::getUsername , username);
        }


        //发起查询 ， 返回User
        User user = userMapper.selectJoinOne(User.class , wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //User -> LoginUser  封装自定义LoginUser认证主体返回
        LoginUser loginUser = new LoginUser(user);
        return loginUser;
    }
}
